package com.rcl.mvvmdemo.musicList

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import com.rcl.mvvmdemo.R
import com.rcl.mvvmdemo.base.BaseActivity
import com.rcl.mvvmdemo.player.domain.Music
import kotlinx.android.synthetic.main.activity_musics.*

class MusicsActivity : BaseActivity() {
    private val musicsPresenter by lazy {
        MusicsPresenter(this)
    }

    private lateinit var mForeverObserve: ForeverObserve

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_musics)
        initDataListener()
        initViewListener()
    }

    inner class ForeverObserve : Observer<List<Music>> {
        override fun onChanged(result: List<Music>?) {
            Log.i("aaaaa", "forever observer data change -->${result?.size}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        musicsPresenter.liveMusicList.removeObserver(mForeverObserve)
    }

    /**
     * 监听数据变化
     */
    private fun initDataListener() {
        /*musicsPresenter.liveMusicList.observe(this,
            Observer<List<Music>> {
                //去更新ui
                Log.i("aaaaa", "live data里的音乐列表数据更新了...${it.size}")
            })*/

        mForeverObserve = ForeverObserve()
        musicsPresenter.liveMusicList.observeForever(mForeverObserve)

        musicsPresenter.musicList.addListener(this) {
            println(Thread.currentThread().name)
            var str = "加载到了-->  ${it?.size}条数据"
            println(str)
            tvMusicNum?.text = str
        }

        musicsPresenter.loadState.addListener(this) {
            println("加载状态 --->  $it")
        }
    }

    private fun initViewListener() {
        getMusicsBtn.setOnClickListener {
            musicsPresenter.getMusic()
        }
    }
}